import { NextRequest, NextResponse } from 'next/server';
import { SD_BASE_URL } from '@/lib/config';
import { getDb } from '@/lib/db';

export async function POST(request: NextRequest) {
  try {
    // 获取请求体数据
    const body = await request.json();

    // 构造转发到目标API的数据对象
    const forwardData = {
      // 必填参数
      image: body.image,
      
      // 可选参数
      resize_mode: body.resize_mode !== undefined ? body.resize_mode : 0,
      show_extras_results: body.show_extras_results !== undefined ? body.show_extras_results : true,
      gfpgan_visibility: body.gfpgan_visibility !== undefined ? body.gfpgan_visibility : 0,
      codeformer_visibility: body.codeformer_visibility !== undefined ? body.codeformer_visibility : 0,
      codeformer_weight: body.codeformer_weight !== undefined ? body.codeformer_weight : 0,
      upscaling_resize: body.upscaling_resize !== undefined ? body.upscaling_resize : 2,
      upscaling_resize_w: body.upscaling_resize_w !== undefined ? body.upscaling_resize_w : 512,
      upscaling_resize_h: body.upscaling_resize_h !== undefined ? body.upscaling_resize_h : 512,
      upscaling_crop: body.upscaling_crop !== undefined ? body.upscaling_crop : true,
      upscaler_1: body.upscaler_1 !== undefined ? body.upscaler_1 : "None",
      upscaler_2: body.upscaler_2 !== undefined ? body.upscaler_2 : "None",
      extras_upscaler_2_visibility: body.extras_upscaler_2_visibility !== undefined ? body.extras_upscaler_2_visibility : 0,
      upscale_first: body.upscale_first !== undefined ? body.upscale_first : false
    };

    // 转发请求到目标API
    const response = await fetch(`${SD_BASE_URL}/sdapi/v1/extra-single-image`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(forwardData)
    });

    // 检查响应状态
    if (!response.ok) {
      const detail = await response.text();
      return NextResponse.json(
        { error: 'Request error', detail, status: response.status },
        { status: response.status }
      );
    }

    // 返回目标API的响应
    const data = await response.json();

    // 入库：记录提交与返回（注意：含 base64 图片，数据较大）
    try {
      const db = await getDb();
      await db.create('extras_records', {
        type: 'extra-single-image',
        createdAt: new Date().toISOString(),
        request: body,        // 原始请求
        forwarded: forwardData, // 实际转发参数
        response: data        // 上游返回
      } as any);
    } catch (persistErr) {
      console.error('保存 extras 记录失败:', persistErr);
    }

    return new Response(JSON.stringify(data), {
      status: 200,
    });

  } catch (error: any) {
    // 处理和返回错误
    const errorResponse = { 
      error: 'Internal Server Error', 
      detail: error.message || 'Unknown error occurred' 
    };
    
    return new Response(JSON.stringify(errorResponse), { 
      status: 500
    });
  }
}